﻿using EleCho.GoCqHttpSdk.Message;
using EleCho.GoCqHttpSdk.Post;
using PluginSdk;
using System.Threading.Channels;

namespace MausBot;

public class MessageStream(Channel<CqMessagePostContext> contexts, Func<CqMessage, Task> postAction, Permission permission, long Gid, long Uid) : IMessageStream
{
    public bool Closed { get; private set; }

    public Permission Permission { get; private set; } = permission;

    public long Gid { get; private set; } = Gid;

    public long Uid { get; private set; } = Uid;

    public void Close()
    {
        Closed = true;
    }

    public async Task<CqMessagePostContext> ReadMessage()
    {
        if (Closed)
            throw new InvalidOperationException("在停用的上下文中读取消息");
        return await contexts.Reader.ReadAsync();
    }

    public async Task WriteMessage(CqMessage message)
    {
        if (Closed)
            throw new InvalidOperationException("在停用的上下文中写入消息");
        await postAction(message);
    }

    public async Task FeedMessage(CqMessagePostContext context)
    {
        await contexts.Writer.WriteAsync(context);
    }
}